class EventBus {
  // 事件列表
  private events: { [key: string]: Function[] } = {};

  // 事件监听
  on(eventName: string, callback: Function) {
    const cbs = this.events[eventName] || [];
    !cbs.includes(callback) && cbs.push(callback);
    this.events[eventName] = cbs;
  }

  // 事件触发
  emit(eventName: string, data?: any) {
    // console.log("🚀 ~ EventBus ~ emit ~ eventName:", eventName);
    const cbs = this.events[eventName];
    if (cbs) {
      cbs.forEach((cb) => cb(data));
    }
  }

  // 移除事件监听
  off(eventName: string, callback?: Function) {
    if (callback) {
      const cbs = this.events[eventName];
      if (cbs) {
        const index = cbs.indexOf(callback);
        if (index > -1) {
          cbs.splice(index, 1);
        }
      }
    } else {
      this.events[eventName] = [];
    }
  }

  once(eventName: string, callback: Function) {
    const onceCallback = (data: any) => {
      callback(data);
      this.off(eventName, onceCallback);
    };
    this.on(eventName, onceCallback);
  }
}

const eventBus = new EventBus();

export { eventBus };
